<template>
  <div class="add-container" v-if="showApplyForm">
    <div class="block">
      <el-form   :model="queryParams">
        <el-select v-model="queryParams.vesselName" filterable clearable placeholder="Vessel" style="width:180px"
          @change="selectVessel(queryParams)">
          <el-option :key="item.vesselName" :label="item.vesselName" :value="item.vesselName" v-for="item in vessels">
          </el-option>
        </el-select>
        &nbsp;&nbsp;
        <el-select v-model="queryParams.voyageNo" filterable clearable placeholder="Voyage"  style="width:120px"> 
          <el-option :key="item.voyageNo" :label="item.voyageNo" :value="item.voyageNo" v-for="item in voyages">
          </el-option>
        </el-select>
          &nbsp;&nbsp;
        <el-input v-model="queryParams.bookingNo" clearable placeholder="Booking No." style="width:120px"/>
        &nbsp;&nbsp; 
        <el-button type="primary" icon="search" @click="search">{{ $t("ship.button.search") }}</el-button>
        <SearchReset :query-params="queryParams" @reset="resetQuery"></SearchReset>
        &nbsp;&nbsp;
        <el-button type="primary" @click="addClickEvent" v-hasPermi="['bookingNoApply:edit']"> Apply</el-button>
      </el-form>
    </div>
    <el-table v-loading="loading" :data="dataList" :border="true"  row-key="bookingNo" @sort-change="handleSortChange" :show-overflow-tooltip="true" >
      <el-table-column label="Booking No" align="center" prop="bookingNo" width="110" :sort-orders="['descending','ascending']" sortable ="custom" />
      <el-table-column label="Vessel Name" align="center" prop="vesselName" width="160" :sort-orders="['descending','ascending']" sortable ="custom"/>
      <el-table-column label="Voyage No." align="center" prop="voyageNo" width="120" :sort-orders="['descending','ascending']" sortable ="custom"/>
      <el-table-column label="POL" align="center" prop="polCode" :sort-orders="['descending','ascending']" sortable ="custom"/>
      <el-table-column label="POD" align="center" prop="podCode" :sort-orders="['descending','ascending']" sortable ="custom"/>
      <el-table-column label="Brand" align="center" prop="brand" width="120" :sort-orders="['descending','ascending']" sortable ="custom"/>
      <el-table-column label="Sales" align="center" prop="sales" />
      <!-- <el-table-column label="Remark" align="center" prop="remark" :show-overflow-tooltip="true" /> -->
      <el-table-column label="Status" align="center" width="80">
        <template #default="scope">
          {{ statuss[scope.row.status] }}
        </template>
      </el-table-column>v-if
      <el-table-column label="Created By" align="center" prop="createBy" width="120" sort-orders="['descending','ascending']" sortable ="custom"/>
      <el-table-column label="Time Created" align="center" prop="createTime" width="150" sort-orders="['descending','ascending']" sortable ="custom"/>
      <el-table-column label="Operation" align="center" width="130" v-hasPermi="['bookingNoApply:edit']">
        <template #default="scope" >
          <span class="btn-primary" @click="handleEditlclick(scope.row)">Edit</span>&nbsp;&nbsp;
          <el-button type="primary" link @click="handleDelete(scope.row)" :disabled="scope.row.status == 1">Delete</el-button> 
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page="queryParams.pageNum" :limit="queryParams.pageSize"
      @pagination="pageQuery" style="float: right" />
  </div>

  <div class="add-container" v-else>
    <div class="form-container">
      <el-form :model="formParam" :rules="addRules" ref="custForm">
        <el-form-item label="Vessel Name" label-width="220px" prop="vesselName" required>
          <el-select v-model="formParam.vesselName" filterable placeholder="Vessel"
            @change="selectVessel(formParam)" style="width: 240px">
            <el-option :key="item.vesselName" :label="item.vesselName" :value="item.vesselName" v-for="item in vessels">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="Voyage" label-width="220px" prop="voyageNo" required>
          <el-select v-model="formParam.voyageNo" filterable placeholder="Voyage" @change="selectPortCode"
            style="width: 240px">
            <el-option :key="item.voyageNo" :label="item.voyageNo" :value="item.voyageNo" v-for="item in voyages">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="POL" label-width="220px" prop="polCode" required>
          <el-select v-model="formParam.polCode" filterable placeholder="POL" style="width: 240px" @change="getPolCode">
            <el-option :key="item.fullPortCode" :label="item.portName"
              :value="item.fullPortCode" v-for="item in pols">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="POD" label-width="220px" prop="podCode" required>
          <el-select v-model="formParam.podCode" filterable placeholder="POD" style="width: 240px" @change="getPodCode">
            <el-option :key="item.fullPortCode" :label="item.portName" 
              :value="item.fullPortCode" v-for="item in pods">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="Brand" label-width="220px" prop="brand" required>
          <el-select v-model="formParam.brand" filterable allow-create placeholder="Brand" style="width: 240px"
            >
            <el-option :key="item.name" :label="item.name" :value="item.name" v-for="item in formParam.brands">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="Sales" label-width="220px" prop="salesId" required>
          <el-select v-model="formParam.salesId" filterable placeholder="Sales" style="width: 240px">
            <el-option :key="item.id" :label="item.username" :value="item.id" v-for="item in sales"/> 
          </el-select>
        </el-form-item>
      </el-form>
      <div class="dialog-footer"> 
        <el-button type="primary" :loading="isLoading" @click="submitApplyForm">Apply</el-button>
        <el-button type="primary" :loading="isLoading" @click="backHandle">List</el-button>
      </div>
      <div class="booking-no">
        <span style="padding-right: 8px">Booking No：</span>
        <span>{{ formParam.bookingNo || "" }}</span>
        <el-icon v-if="formParam.bookingNo">
          <DocumentCopy @click="copyText(formParam.bookingNo || '123')" />
        </el-icon>
      </div>
    </div>
  </div>
  <el-dialog :width="800" destroy-on-close draggable :title="dialogTitle" v-model="viewDialogFormVisible">
    <el-form :model="formParam" :rules="addRules" ref="custForm">
      <el-form-item label="Vessel Name" label-width="220px" prop="vesselName" required>
        <el-select v-model="formParam.vesselName" filterable placeholder="choose Vessel"
          @change="selectVessel(formParam)" style="width: 100%">
          <el-option :key="item.vesselName" :label="item.vesselName" :value="item.vesselName" v-for="item in vessels">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="Voyage No." label-width="220px" prop="voyageNo" required>
        <el-select v-model="formParam.voyageNo" filterable placeholder="choose Voyage" @change="selectPortCode"
          style="width: 100%">
          <el-option :key="item.voyageNo" :label="item.voyageNo" :value="item.voyageNo" v-for="item in voyages">
          </el-option>
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="POL" label-width="220px" prop="pol" required>
        <el-select v-model="formParam.pol" filterable placeholder="choose pol" style="width: 100%">
          <el-option :key="item.countryCode + item.portCode" :label="item.portName"
            :value="item.countryCode + item.portCode" v-for="item in formParam.pols">
          </el-option>
        </el-select>
      </el-form-item> -->
      <el-form-item label="POD" label-width="220px" prop="pod" required>
        <el-select v-model="formParam.podCode" filterable placeholder="choose pod" @change="podChange" style="width: 100%">
          <el-option :key="item.fullPortCode" :label="item.portName"
            :value="item.fullPortCode" v-for="item in pods">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="Brand" label-width="220px" prop="brand" required>
        <el-select v-model="formParam.brand" filterable allow-create placeholder="choose brand" style="width: 100%"
          >
          <el-option :key="item.name" :label="item.name" :value="item.name" v-for="item in formParam.brands">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="Sales" label-width="220px" prop="salesId" required>
        <el-select v-model="formParam.salesId" filterable placeholder="choose sale" style="width: 100%">
          <el-option :key="item.id" :label="item.username" :value="item.id" v-for="item in sales"> </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div class="dialog-footer">
      <el-button type="primary" :loading="isLoading" @click="viewDialogFormVisible = false">Close</el-button>
      <el-button type="primary" :loading="isLoading" @click="submitApplyForm">Submit</el-button>
    </div>
  </el-dialog>

</template>

<script setup name="bookingNoApply">
// @ts-nocheck
import service from "@/utils/request";
import { ref, onMounted, getCurrentInstance, reactive, toRefs } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { getUserByRoleApi } from "@/api/booking/unfreighted";
import { hasAuth } from "@/utils/auth";
import { useMixinAuth } from "@/components/mixin/auth.js";
const auth = useMixinAuth();
import path from "path";
const route = useRoute();
const router = useRouter();

const { proxy } = getCurrentInstance();
const bookingList = ref([]);
const loading = ref(false);
const showSearch = ref(true);
const total = ref(0);

const statuss = ['Unused', 'Used']
let showApplyForm = route.query?.showApplyForm

const addRules = ref({
vesselname: [{ required: true, message: "Vessel Name is required" }],
voyageNo: [{ required: true, message: "Voyage is required" }],
polCode: [{ required: true, message: "POL is required" }],
podCode: [{ required: true, message: "POD is required" }],
brand: [{ required: true, message: "Brand is required" }],
salesId: [{ required: true, message: "Sales is required" }],
});
let pols = reactive([])
let pods = reactive([])
const data = reactive({
form: {},
dataList: ref([]),
queryParams: {
  pageNum: 1,
  pageSize: 20,
  vesselName: undefined,
  voyageNo: undefined,
  status: undefined,
  orderByColumn: '',
  isAsc: undefined
},
vessels: reactive([]),
voyages: [],
formParam: {  
  pols: [],
  pods: [],
  brands: [],
  clients:[],
  vesselName: "",
  voyageNo: "",
  pol: null,
  polCode: null,
  pod: null,
  podCode:null,
  brand: "",
  salesId: null
},
rules: {
  vesselName: [{ required: true, message: "Vessel Name cann't be blank", trigger: "blur" }],
  voyageNo: [{ required: true, message: "Voyage cann't be blank", trigger: "blur" }],
  pol: [{ required: true, message: "POL can't be null", trigger: "blur" }],
  pod: [{ required: true, message: "POD can't be null", trigger: "blur" }],
  brand: [{ required: true, message: "Brand can't be null", trigger: "blur" }],
  sales: [{ required: true, message: "Sale can't be null", trigger: "blur" }]
}
});

const { queryParams, form, dataList, rules, formParam } = toRefs(data);

/** 取消按钮 */
function cancel() {
router.push({ path: "/booking/list/apply" });
reset();
}
/** 表单重置 */
function reset() {
const params = {
  vesselName: "",
  voyageNo: "",
  pol: "",
  pod: "",
  brand: "",
  sales: ""
};
Object.keys(params).forEach(key => {
  formParam.value[key] = params[key];
});
}
 
const pageQuery = async (e) => {
  queryParams.value.pageNum = e.page;
  queryParams.value.pageSize = e.limit;
  getList();
};

const search = () => { 
  getList();
}

  /** 搜索按钮操作 */
  function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
  }
  /** 重置按钮操作 */
  const resetQuery = (data) => {
    Object.assign(queryParams, data)
    dataList.value = []
  }
  /** 新增按钮操作 */
  function handleAdd() {
    reset();
    isTable.value = false;
  }

  /** 删除按钮操作 */
  function handleDelete(row) {
    proxy.$modal.confirm('confirm to remove the data"').then(function () {
      return service.delete(`/shipping/bookingNoApply/` + row.id);
    }).then(() => {
      getList();
      proxy.$modal.msgSuccess("delete success");
    }).catch(() => { });
  }

  const vesselNameChange = () => {
    formParam.value.voyageNo = null
    formParam.value.pol = null
    formParam.value.pod = null
  }
  // 提交申请
  const isLoading = ref(false);
  const custForm = ref(null);
  const submitApplyForm = () => {
    custForm.value.validate(async valid => {
      if (valid) {
        const { vesselName, voyageNo, pol, pod, brand, salesId,id,podCode,polCode } = formParam.value;

        if (id != undefined) {
          service
            .put("/shipping/bookingNoApply", { vesselName, voyageNo, pol, pod, brand, salesId,id,podCode,polCode })
            .then(result => {
              proxy.$modal.msgSuccess("Update Success");
              viewDialogFormVisible.value = false
              getList();
            })
        } else {
          if (isLoading.value) return;
          isLoading.value = true;
          service
            .post("/shipping/bookingNoApply", { vesselName, voyageNo, pol, pod, brand, salesId,podCode,polCode })
            .then(result => {
              if (result && result.data) {
                formParam.value.bookingNo = result.data || "";
              }
            })
            .finally(() => {
              isLoading.value = false;
            });
        }
      }
    });
  };
  const backHandle = () => {
    router.push({ path: '/booking/bookingApply', query: { showApplyForm: false }  })
    showApplyForm = true
  }

  const handleBrand = async (value) => {
    const isOptionSelected = formParam.value.brands.some(option => option.value === value);
    if (!isOptionSelected) { 
      await service.post("/shipping/brand", { name: value })
    }
  }

  const addClickEvent = () => {
    router.push({ path: '/booking/list/apply'})
    showApplyForm = false
  }
  let voyages = reactive([])
  const selectVessel = value => {
    queryParams.value.voyageNo = null
    voyages = []
    formParam.value.voyageNo = null
    formParam.value.pol = null
    formParam.value.pod = null
    voyages = (vessels.find(item => item.vesselName == value.vesselName) || { schedules: [] }).schedules;
  };

  const selectPortCode = value => {
    pods = (voyages.find(item => item.voyageNo == value) || { pods: [] }).pods;
    pols = (voyages.find(item => item.voyageNo == value) || { pols: [] }).pols; 
  };
  const podChange = (value) => {
    let item = pods.find(n=>n.fullPortCode==value)  
    formParam.value.pod = item.portName  
  }
  
/** 排序触发事件 */
function handleSortChange(column) {  
  queryParams.value.orderByColumn = column.prop;
  queryParams.value.isAsc = column.order;
  getList();
}

 

  const copyText = code => {
    if (!code) return;
    const oInput = document.createElement("textarea");
    oInput.value = code;
    document.body.appendChild(oInput);
    oInput.select(); // 选择对象;
    document.execCommand("Copy"); // 执行浏览器复制命令
    ElMessage({
      message: "Copy Success",
      type: "success"
    });
    oInput.remove();
  };

  const getList = async () => {
    let result = await service.get("/shipping/bookingNoApply/getTable", { params: queryParams.value });
    if (result) {
      total.value = result.total
      dataList.value = result.data
    }
  }

  const getPolCode = (val)=>{   
    let item = pols.find(n=>n.fullPortCode==val)  
    console.log(item)
    formParam.value.pol = item.portName
  }
  const getPodCode = (val)=>{
    let item = pods.find(n=>n.fullPortCode==val) 
    formParam.value.pod = item.portName
  }

  const sales = ref([]);
  let vessels = reactive([]);

  // 编辑功能
  const dialogTitle = ref()
  const viewDialogFormVisible = ref(false);
  const handleEditlclick = (row) => {
    dialogTitle.value = "Edit";
    viewDialogFormVisible.value = true;
    Object.keys(row).forEach((k) => (formParam.value[k] = row[k])); 
    voyages = (vessels.find(item => item.vesselName == formParam.value.vesselName) || { schedules: [] }).schedules; 
    pods = (voyages.find(item => item.voyageNo == formParam.value.voyageNo) || { pods: [] }).pods; 
    pols = (voyages.find(item => item.voyageNo == formParam.value.voyageNo) || { pols: [] }).pols;  
  }

  onMounted(async () => {
    let vesselsList = await service.get("/shipping/schedule/getAllSchedule");
    if (vesselsList) {
      vessels = vesselsList.data;
    }
    let result = await service.get("/shipping/brand/list");
    if (result) {
      formParam.value.brands = result.data;
    }
   
    getUserByRoleApi({ roleName: "sales" }).then(res => {
      sales.value = (res.data || []).map(({ id, username }) => ({ id, username }));
    });
    getList()
  });
</script>
<style lang="scss" scoped>
  .add-container {
    padding-top: 30px;
    background-color: #fafafa;
    height: 100%;
  }

  .query-wrapper{
    width: 600px
  }

  .form-container {
    margin: auto;
    padding: 40px;
    width: 800px;
    background-color: #fff;
  }

  .el-select {
    width: 380px;
  }

  .dialog-footer {
    margin: 60px auto 0;
    width: 100%;
    text-align: center;
  }

  .booking-no {
    padding: 30px 0 20px;
    text-align: center;

    span {
      font-size: 30px;
      font-weight: 700;
      padding-right: 4px;
    }

    .el-icon {
      font-size: 24px;

      &:hover {
        cursor: pointer;
      }
    }
  }
</style>